package com.markhsiu.common.memory;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

import com.markhsiu.common.thread.TaskFactory;

public class ThreadAllocPool {

	private static final AtomicInteger count = new AtomicInteger(0);
	public static void main(String[] args) throws Exception {
		
		long start = System.currentTimeMillis();
		MemoryPool pool = new MemoryPool(10);
		System.out.println("新建pool "+(System.currentTimeMillis() - start));
		System.out.println("初始化："+pool.remian()/1024+" kb");
		
		try {
			for (int i = 0; i < 10000; i++) {
				TaskFactory.execute(new Callable<Integer>() {

					@Override
					public Integer call() throws Exception {
						
						ByteBuff buff = pool.alloc(1024*102);
//						System.out.println("分配："+buff.capacity()/1024+" kb");
//						System.out.println("剩余："+pool.remian()/1024+" kb");
						for (int j = 0; j < 10; j++) {
							buff.putInt(10);
							buff.putInt(30);
						}
//						System.out.println(buff);
						byte[] data = buff.data();
//						System.out.println("===========");
//						System.out.println("*******************");
//						System.out.println(Bits.toInt(data[0], data[1], data[2], data[3]));
//						System.out.println(Bits.toInt(data[4], data[5], data[6], data[7]));
						
						
//						System.out.println("*******************");
						ByteBuff  buff1 = pool.alloc(104500);
//						System.out.println("分配："+buff1.capacity()/1024+" kb");
//						System.out.println("剩余："+pool.remian()/1024+" kb");
						for (int j = 0; j < 10; j++) {
							buff1.put(data);
						}
						
						data = buff1.data();
//						System.out.println(data.length);
//						System.out.println(new String(data,"UTF-8"));
//						System.out.println("*******************");
						pool.free(buff);
						pool.free(buff1);
//						System.out.println("释放。。。buff");	
//						System.out.println("buff："+buff.capacity()/1024+" kb");
//						System.out.println(")))))))))))))))))))))))))))))))))))");
						System.out.println();
						return count.incrementAndGet();
					}
					
				}, "你好");
			}
		} finally {
			 
		}
		
		
		System.out.println("pool："+pool.remian()/1024+" kb");
		System.out.println("总花费 "+(System.currentTimeMillis() - start));
	
	
	}
}
